package com.threeox.commonlibrary.config;

import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.threeox.commonlibrary.CommonApplcation;
import com.threeox.commonlibrary.R;
import com.threeox.commonlibrary.config.inter.IListModelViewConfig;
import com.threeox.commonlibrary.config.inter.IModelViewConfig;
import com.threeox.commonlibrary.config.inter.IMultiPageModelConfig;
import com.threeox.commonlibrary.config.inter.ITableModelViewConfig;
import com.threeox.commonlibrary.entity.engine.model.layout.ModelMessage;
import com.threeox.commonlibrary.entity.engine.model.listmodel.ListModelMsg;
import com.threeox.commonlibrary.entity.engine.model.multipage.MultiPageMessage;
import com.threeox.commonlibrary.entity.engine.model.table.TableModelMessage;
import com.threeox.commonlibrary.entity.engine.request.RequestMsg;
import com.threeox.commonlibrary.inter.IOverallConfig;
import com.threeox.commonlibrary.util.engine.AnnotationUtil;
import com.threeox.utillibrary.util.EmptyUtils;
import com.threeox.utillibrary.util.LogUtils;
import com.threeox.utillibrary.util.encdec.EncodeUtils;
import com.threeox.utillibrary.util.res.DrawableHelper;
import com.threeox.utillibrary.util.res.IdHelper;
import com.threeox.utillibrary.util.res.LayoutHelper;
import com.threeox.utillibrary.util.res.RawHelper;
import com.threeox.utillibrary.util.res.StringHelper;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * @ClassName: CommonConfig
 *
 * @Description: TODO(模型库的配置类 单例类)
 *
 * @author 赵屈犇
 *
 * @date 创建时间:2017/3/3 16:57
 *
 * @version 1.0
 *
 */
public class CommonConfig {

    private static CommonConfig mInstance = null;

    private CommonApplcation mApplcation;
    private final String TAG = CommonConfig.class.getName();

    // 请求对象集合
    private Map<Object, RequestMsg> mRequestMessages = new HashMap<Object, RequestMsg>();
    // 布局模型对象集合
    private Map<Object, ModelMessage> mModelMessages = new HashMap<Object, ModelMessage>();
    // 列表模型对象集合
    private Map<Object, ListModelMsg> mListModelMessages = new HashMap<Object, ListModelMsg>();
    // 表格模型对象集合
    private Map<Object, TableModelMessage> mTableModelMessages = new HashMap<Object, TableModelMessage>();
    // 多页面模型对象集合
    private Map<Object, MultiPageMessage> mMultiPageMessages = new HashMap<Object, MultiPageMessage>();
    // JSON对象的对象集合
    private Map<Object, JSONObject> jsonObjectMessages = new HashMap<Object, JSONObject>();

    private JSONObject modelData = null;

    private IdHelper idHelper = null;
    private RawHelper rawHelper = null;
    private StringHelper stringHelper = null;
    private LayoutHelper layoutHelper = null;
    private DrawableHelper drawableHelper = null;
    private AnnotationUtil mAnnotationUtil = null;

    private String OVERALL_EXTEND = "", MODELVIEW_EXTEND = "", LISTMODEL_EXTEND = "", MULTIPAGE_EXTEND = "", TABLEMODEL_EXTEND = "";

    public static CommonConfig getInstance() {
        if (mInstance == null) {
            synchronized (CommonConfig.class) {
                if (mInstance == null) {
                    mInstance = new CommonConfig();
                }
                return mInstance;
            }
        }
        return mInstance;
    }

    private CommonConfig() {
        try {
            mApplcation = CommonApplcation.getInstance();
            ApplicationInfo appInfo = mApplcation.getPackageManager().getApplicationInfo(mApplcation.getPackageName(), PackageManager.GET_META_DATA);
            Bundle metaData = appInfo.metaData;
            initHelperObj();
            if (metaData != null) {
                String overallName = stringHelper.getString(R.string.overall_extend);
                if (metaData.containsKey(overallName)) {
                    this.OVERALL_EXTEND = metaData.getString(overallName);
                }
                String modelviewName = stringHelper.getString(R.string.modelview_extend);
                if (metaData.containsKey(modelviewName)) {
                    this.MODELVIEW_EXTEND = metaData.getString(modelviewName);
                }
                String listModelViewName = stringHelper.getString(R.string.listmodelview_extend);
                if (metaData.containsKey(listModelViewName)) {
                    this.LISTMODEL_EXTEND = metaData.getString(listModelViewName);
                }
                String tableModelViewName = stringHelper.getString(R.string.tablemodelview_extend);
                if (metaData.containsKey(tableModelViewName)) {
                    this.TABLEMODEL_EXTEND = metaData.getString(tableModelViewName);
                }
                String multiPageViewName = stringHelper.getString(R.string.multipageview_extend);
                if (metaData.containsKey(multiPageViewName)) {
                    this.MULTIPAGE_EXTEND = metaData.getString(multiPageViewName);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化各种帮助类
     */
    private void initHelperObj() {
        this.idHelper = IdHelper.newInstance(mApplcation);
        this.rawHelper = RawHelper.newInstance(mApplcation);
        this.stringHelper = StringHelper.newInstance(mApplcation);
        this.layoutHelper = LayoutHelper.newInstance(mApplcation);
        this.drawableHelper = DrawableHelper.newInstance(mApplcation);
        this.mAnnotationUtil = AnnotationUtil.getInstance(mApplcation);
    }

    /*=======================列表模型函数========================*/

    /**
     * 得到列表模型数据
     *
     * @param resId
     * @return
     */
    public ListModelMsg getListModelMsg(Object resId) {
        ListModelMsg result = null;
        try {
            ListModelMsg listModelMsg = mListModelMessages.get(resId);
            if (listModelMsg == null) {
                String message = getEngineMessage(resId);
                if (EmptyUtils.isNotEmpty(message)) {
                    listModelMsg = JSON.parseObject(message, ListModelMsg.class);
                    String listModelExtendName = mAnnotationUtil.getListModelExtendClass(resId);
                    if (EmptyUtils.isEmpty(listModelMsg.getExtendName())) {
                        listModelMsg.setExtendName(listModelExtendName);
                    }
                    listModelMsg.initData(this.stringHelper, this.layoutHelper, this.idHelper);
                }
                mListModelMessages.put(resId, listModelMsg);
            }
            result = listModelMsg.copyObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /*private String getListModelMsgText(Object resId) {
        if (mListModelMsgs.containsKey(resId)) {
            return mListModelMsgs.get(resId);
        }
        try {
            String msg = getEngineMessage(resId);
            if (EmptyUtils.isNotEmpty(msg)) {
                mListModelMsgs.put(resId, msg);
                return msg;
            }
            return null;
        } catch (Exception e) {
            return null;
        }
    }*/

    /**
     * 得到列表模型的全局扩展类
     *
     * @return
     */
    public IListModelViewConfig getListModelViewExtend() {
        if (EmptyUtils.isNotEmpty(LISTMODEL_EXTEND)) {
            try {
                return (IListModelViewConfig) Class.forName(LISTMODEL_EXTEND).newInstance();
            } catch (Exception e) {
                LogUtils.e(TAG, "getListModelViewExtend===>>" + e.getMessage());
                return null;
            }
        }
        return null;
    }

    /*=======================列表模型函数========================*/

    /*=======================页面模型函数========================*/

    /**
     * 得到布局模型的对象
     *
     * @param resId
     * @return
     */
    public ModelMessage getModelMessage(Object resId) {
        ModelMessage result = null;
        try {
            ModelMessage modelMessage = mModelMessages.get(resId);
            if (modelMessage == null) {
                String message = getEngineMessage(resId);
                if (EmptyUtils.isNotEmpty(message)) {
                    modelMessage = JSON.parseObject(message, ModelMessage.class);
                    String modelExtendName = mAnnotationUtil.getModelExtendClass(resId);
                    if (EmptyUtils.isEmpty(modelMessage.getExtendName())) {
                        modelMessage.setExtendName(modelExtendName);
                    }
                    modelMessage.initData(stringHelper, drawableHelper, layoutHelper, idHelper);
                }
                mModelMessages.put(resId, modelMessage);
            }
            result = modelMessage.copyObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /*public String getModelMessageText(Object resId) {
        if (mModelMessages.containsKey(resId)) {
            return mModelMessages.get(resId);
        }
        try {
            String msg = getEngineMessage(resId);
            if (EmptyUtils.isNotEmpty(msg)) {
                mModelMessages.put(resId, msg);
                return msg;
            }
            return null;
        } catch (Exception e) {
            return null;
        }
    }*/

    /**
     * 得到布局模型的全局扩展类
     *
     * @return
     */
    public IModelViewConfig getModelViewExtend() {
        if (EmptyUtils.isNotEmpty(MODELVIEW_EXTEND)) {
            try {
                return (IModelViewConfig) Class.forName(MODELVIEW_EXTEND).newInstance();
            } catch (Exception e) {
                LogUtils.e(TAG, "getModelViewExtend===>>" + e.getMessage());
                return null;
            }
        }
        return null;
    }

    /**
     * 得到ViewControl配置的对象
     *
     * @return
     */
    public JSONObject getViewControl() {
        if (modelData == null) {
            modelData = JSON.parseObject(rawHelper.readText(R.raw.model));
            JSONObject subObj = JSON.parseObject(rawHelper.readText(R.raw.sub_model));
            if (subObj != null) {
                modelData.putAll(subObj);
            }
        }
        return modelData;
    }

    /*=======================页面模型函数========================*/

    /*=======================表格模型函数========================*/

    /**
     * 得到表格模型对象
     *
     * @param resId
     * @return
     */
    public TableModelMessage getTableModelMessage(Object resId) {
        TableModelMessage result = null;
        try {
            TableModelMessage tableModelMessage = mTableModelMessages.get(resId);
            if (tableModelMessage == null) {
                String message = getEngineMessage(resId);
                if (EmptyUtils.isNotEmpty(message)) {
                    tableModelMessage = JSON.parseObject(message, TableModelMessage.class);
                    String modelExtendName = mAnnotationUtil.getTableModelExtendClass(resId);
                    if (EmptyUtils.isEmpty(tableModelMessage.getExtendName())) {
                        tableModelMessage.setExtendName(modelExtendName);
                    }
                    tableModelMessage.initData(stringHelper, idHelper, layoutHelper);
                }
                mTableModelMessages.put(resId, tableModelMessage);
            }
            result = tableModelMessage.copyObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /*public String getTableModelMessageText(Object resId) {
        if (mTableModelMessage.containsKey(resId)) {
            return mTableModelMessage.get(resId);
        }
        try {
            String msg = getEngineMessage(resId);
            if (EmptyUtils.isNotEmpty(msg)) {
                mTableModelMessage.put(resId, msg);
                return msg;
            }
            return null;
        } catch (Exception e) {
            return null;
        }
    }*/

    /**
     * 得到布局模型的全局扩展类
     *
     * @return
     */
    public ITableModelViewConfig getTableModelViewExtend() {
        if (EmptyUtils.isNotEmpty(TABLEMODEL_EXTEND)) {
            try {
                return (ITableModelViewConfig) Class.forName(TABLEMODEL_EXTEND).newInstance();
            } catch (Exception e) {
                LogUtils.e(TAG, "getTableModelViewExtend===>>" + e.getMessage());
                return null;
            }
        }
        return null;
    }

    /*=======================表格模型函数========================*/

    /*=======================多页面模型函数========================*/

    /**
     * 得到多页面模型的对象
     *
     * @param resId
     * @return
     */
    public MultiPageMessage getMultiPageMessage(Object resId) {
        MultiPageMessage result = null;
        try {
            MultiPageMessage multiPageMessage = mMultiPageMessages.get(resId);
            if (multiPageMessage == null) {
                String message = getEngineMessage(resId);
                if (EmptyUtils.isNotEmpty(message)) {
                    multiPageMessage = JSON.parseObject(message, MultiPageMessage.class);
                    String modelExtendName = mAnnotationUtil.getMultiPageExtendClass(resId);
                    if (EmptyUtils.isEmpty(multiPageMessage.getExtendName())) {
                        multiPageMessage.setExtendName(modelExtendName);
                    }
                    multiPageMessage.initData(stringHelper, idHelper, layoutHelper);
                }
                mMultiPageMessages.put(resId, multiPageMessage);
            }
            result = multiPageMessage.copyObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /*public String getMultiPageMessageText(Object resId) {
        if (mMultiPageMessages.containsKey(resId)) {
            return mMultiPageMessages.get(resId);
        }
        try {
            String msg = getEngineMessage(resId);
            if (EmptyUtils.isNotEmpty(msg)) {
                mMultiPageMessages.put(resId, msg);
                return msg;
            }
            return null;
        } catch (Exception e) {
            return null;
        }
    }*/

    /**
     * 得到多页面模型的全局扩展类
     *
     * @return
     */
    public IMultiPageModelConfig getMultiPageViewExtend() {
        if (EmptyUtils.isNotEmpty(MULTIPAGE_EXTEND)) {
            try {
                return (IMultiPageModelConfig) Class.forName(MULTIPAGE_EXTEND).newInstance();
            } catch (Exception e) {
                LogUtils.e(TAG, "getMultiPageViewExtend===>>" + e.getMessage());
                return null;
            }
        }
        return null;
    }

    /*=======================多页面模型函数========================*/


    /*=======================请求对象模型函数========================*/
    /**
     * 得到布局模型的对象
     *
     * @param resId
     * @return
     */
    public RequestMsg getRequestMessage(Object resId) {
        try {
            if (mRequestMessages.containsKey(resId)) {
                return mRequestMessages.get(resId);
            }
            String message = getRequestMessageText(resId);
            if (EmptyUtils.isNotEmpty(message)) {
                RequestMsg data = JSON.parseObject(message, RequestMsg.class);
                data.initData(stringHelper);
                return data;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String getRequestMessageText(Object resId) {
        try {
            String msg = getEngineMessage(resId);
            if (EmptyUtils.isNotEmpty(msg)) {
                return msg;
            }
            return null;
        } catch (Exception e) {
            return null;
        }
    }
    /*=======================请求对象模型函数========================*/


    /*=======================JSON对象模型函数========================*/
    /**
     * 得到JSON包装JSON对象
     *
     * @param resName
     * @return
     */
    public JSONObject getJSONMessage(Object resName) {
        try {
            if (jsonObjectMessages.containsKey(resName)) {
                return jsonObjectMessages.get(resName);
            }
            String message = getEngineMessage(resName);
            if (EmptyUtils.isNotEmpty(message)) {
                JSONObject data = JSON.parseObject(message);
                jsonObjectMessages.put(resName, data);
                return data;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /*=======================JSON对象模型函数========================*/

    /**
     *
     * 得到引擎的消息
     *
     * @param data
     * @return
     */
    private String getEngineMessage(Object data) {
        String msg = null;
        if (data != null) {
            String message = null;
            if (data instanceof Integer) {
                message = rawHelper.readText((Integer) data);
            } else if (data instanceof String) {
                message = rawHelper.readText((String) data);
            }
            if (EmptyUtils.isNotEmpty(message)) {
                msg = new String(EncodeUtils.base64Decode(message));
            }
        }
        return msg;
    }

    /**
     * 得到全局的扩展类
     *
     * @return
     */
    public IOverallConfig getOverallExtend() {
        if (EmptyUtils.isNotEmpty(OVERALL_EXTEND)) {
            try {
                return (IOverallConfig) Class.forName(OVERALL_EXTEND).newInstance();
            } catch (Exception e) {
                LogUtils.e(TAG, "getOverallExtend===>>" + e.getMessage());
                return null;
            }
        }
        return null;
    }

}
